from flask import g
from playhouse.shortcuts import model_to_dict

from models.user import Role, UserRolePermission
from utils.views import get_page
from components.base_log import log_method_call


@log_method_call(action='Create')
def add_role_info():
    Role.create(
        name=g.json.get('name')
    )


@log_method_call(action='Retrieve')
def get_roles():
    conditions = [Role.is_del == False]
    if getattr(g, 'search_name', None):
        conditions.append(Role.name ** ('%{}%'.format(g.search_name)))
    if hasattr(g, 'search_status'):
        if g.search_status:
            conditions.append(Role.enable == g.search_status)
        else:
            conditions.append(Role.enable << [True, False])
    data = {'items': []}
    query = Role.select().where(*conditions)
    if g.page:
        data['page'] = get_page(query)
        query = query.paginate(g.page, g.per_page)
    for role in query:
        data['items'].append(model_to_dict(role))
    return data


@log_method_call(action='Update')
def role_enable_status(status=True):
    role = Role.get_or_none(Role.id == g.json.get('role_id'))
    if status:
        role.enable = True
    else:
        role.enable = False
    role.save()
    return model_to_dict(role)


@log_method_call(action='Retrieve')
def get_role_info(pk):
    role = Role.get_or_none(Role.id == pk)
    return model_to_dict(role)


@log_method_call(action='Retrieve')
def get_role_permission(pk):
    permissions = UserRolePermission.select().where(UserRolePermission.role_id == pk, UserRolePermission.is_del == False)
    return [permission.permission_id for permission in permissions]


@log_method_call(action='Retrieve')
def change_role_permission():
    role_id = g.json.get('role_id')
    id_list = g.json.get('id_list')
    permissions = UserRolePermission.delete().where(UserRolePermission.role_id == role_id)
    permissions.execute()
    for role_permission_id in id_list:
        UserRolePermission.create(
            role_id=role_id,
            permission_id=role_permission_id
        )
    return id_list
